package com.pocket.demo.core.mq.rabbitMQ.demo;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.FanoutExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.context.annotation.Bean;

/**
 * @author cookie. 【demo-MQ-rabbitMQ-2】
 *  * <p> ERROR : Broker not available; cannot force queue declarations during start: java.io.IOException <br>
 *  * 原因：权限问题，连接虚拟机不对
 **/
//@Configuration
//@Import({FanoutPublisher.class, FanoutConsumer.class})
public class FanoutExchangeConfig {

    private static final Logger LOGGER = LoggerFactory.getLogger(FanoutExchangeConfig.class);

    public static final String FANOUT_EXCHANGE = "pocket.fanout";
    public static final String FANOUT_QUEUE_1 = "pocket.fanout.queue_1";
    public static final String FANOUT_QUEUE_2 = "pocket.fanout.queue_2";

    @Bean
    public MessageConverter messageConverter(){
        // 1.定义消息转换器
        Jackson2JsonMessageConverter jackson2JsonMessageConverter = new Jackson2JsonMessageConverter();
        // 2.配置自动创建消息id，用于识别不同消息，也可以在业务中基于ID判断是否是重复消息
        jackson2JsonMessageConverter.setCreateMessageIds(true);
        return jackson2JsonMessageConverter;
    }

    @Bean
    public FanoutExchange fanoutExchange(){
        return new FanoutExchange(FANOUT_EXCHANGE, true, false);
    }

    @Bean
    public Queue fanoutQueue1(){
        return new Queue(FANOUT_QUEUE_1);
    }

    @Bean
    public Queue fanoutQueue2(){
        return new Queue(FANOUT_QUEUE_2);
    }

    @Bean
    public Binding bindingQueue1(Queue fanoutQueue1, FanoutExchange fanoutExchange){
        LOGGER.debug("RabbitMQ : 绑定队列【{}】到交换机【{}】", fanoutQueue1.getName(), fanoutExchange.getName());
        return BindingBuilder.bind(fanoutQueue1).to(fanoutExchange);
    }

    @Bean
    public Binding bindingQueue2(Queue fanoutQueue2, FanoutExchange fanoutExchange){
        LOGGER.debug("RabbitMQ : 绑定队列【{}】到交换机【{}】", fanoutQueue2.getName(), fanoutExchange.getName());
        return BindingBuilder.bind(fanoutQueue2).to(fanoutExchange);
    }
}
